/**
 * @file 工单操作-派单
 * @author yangjiangming <449654337@qq.com>
 * @date 2018-12-10 20:13:16
 */
layui.define(['layer', 'form', 'element', 'table', 'zmnUtils', 'select2', '$http', '$api'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;

    var zmnUtils = layui.zmnUtils;
    var opCommonUtils = layui.list_modify_common;
    var $http = layui.$http;
    var $api = layui.$api;
    var select2 = layui.select2;

    var allMasterList = json.recommendMasterList;
    var partMaterList = filtrateMasterListByGroupId(allMasterList, json.mainSkillId);

    // 工程师远程查询 URL
    var MASTER_LIST_URL = '/staff/master/list.action';
    // 校验工程师派单
    var MASTER_CHECK_URL = '/work/modify/distribute/checkReason.action';
    // 获取工程师库存
    var GET_MASTER_STOCK_URL = '/work/modify/master/stock.action';

    var templeteFormatter = {
        masterInfoTempleteFunc: function (d) {
            return '<div><span class="master" id="' + d.masterId + '"></span></div>';
        },
        masterNameTempleteFunc: function (d) {
            var text = d.masterName + '—' + zmnUtils.maskPhone(d.masterPhone);
            var isReworkMaster = json.reworkMasterId === d.masterId;
            var showVoice = d.nonDistributeFlag === undefined;

            return (`
               <div>
                   <div>
                        <span>${text}</span>
                        ${d.distributeRuleTitle ? `<span class="layui-badge layui-bg-green">${d.distributeRuleTitle}</span>` : ''}
                        ${d.novice ? `<span style="background-color: #669900 !important;" class="layui-badge">新手</span>` : ``}
                        ${d.channelExclusive ? `<span style="background-color: #FF6699 !important;" class="layui-badge">专属</span>` : ``}
                        ${isReworkMaster ? '<span class="layui-badge">源工程师</span>' : ''}
                        ${d.useStock ? `<span class="layui-badge layui-bg-green btn-stock" data-id="${ d.masterId }">库存</span>` : ''}
                        ${canNetCall && showVoice ? `<a class="zmn-btn-text btn-netcall" data-id="${d.masterId}"><i class="zmn-icon zmn-icon-voice"></i></a>` : ''}
                    </div>
                </div>
            `);
        },
        MapMasterNameTempleteFunc: function (d) {
            var text = d.masterName + '—' + zmnUtils.maskPhone(d.masterPhone);
            var jia = d.companyId == 45111;
            if (jia) {
                text += "-家";
            }
            var isReworkMaster = json.reworkMasterId === d.masterId;
            var showVoice = d.nonDistributeFlag === undefined;

            return (`
               <div>
                   <div>
                        <span>${text}</span>
                        ${canNetCall && showVoice ? `<a class="zmn-btn-text btn-netcall" data-id="${d.masterId}"><i class="zmn-icon zmn-icon-voice"></i></a>` : ''}
                        <br>
                        ${d.distributeRuleTitle ? `<span class="layui-badge layui-bg-green">${d.distributeRuleTitle}</span>` : ''}
                        ${d.agent == 1 ? `<span class="layui-badge agent">直</span>` : `<span class="layui-badge no-agent">非</span>`}
                        ${d.novice ? `<span style="background-color: #669900 !important;" class="layui-badge">新手</span>` : ``}
                        ${d.channelExclusive ? `<span style="background-color: #FF6699 !important;" class="layui-badge">专属</span>` : ``}
                        ${isReworkMaster ? '<span class="layui-badge">源工程师</span>' : ''}
                    </div>
                </div>
            `);
        }
    }

    function nonDistributeAndDistributeFunc(flag, value) {
        return value;
        /*if (flag === undefined) {
            return value;
        } else {
            return "-"
        }*/
    }

    /**
     * 最优库存处理
     * @param value
     * @returns {string|string}
     */
    function processStockType (value) {
        if (value == 0) {
            return '<span class="layui-badge layui-bg-blue">满足</span>';
        } else if (value == 1 || value == 2) {
            return '<span class="layui-badge layui-bg-gray">不满足</span>';
        } else {
            return '-'
        }
    }

    /**
     * 处理单时比，保留3位小数
     * @param flag
     * @param value
     * @returns {string|*}
     */
    function processDatumOrderHourRatio (flag, value) {
        return changeDecimalBuZero(value, 3);
        /*if (flag === undefined) {
            return changeDecimalBuZero(value, 3);
        } else {
            return "-"
        }*/
    }

    /**
     * 单时比小数位处理
     * @param number
     * @param bitNum
     * @returns {string|number}
     */
    function changeDecimalBuZero(number, bitNum) {
        /// 小数位不够，用0补足位数
        number = number/1000;
        var f_x = parseFloat(number);
        if (isNaN(f_x)) {
            return '0.000';
        }
        var s_x = number.toString();
        var pos_decimal = s_x.indexOf('.');
        if (pos_decimal < 0) {
            pos_decimal = s_x.length;
            s_x += '.';
        }
        while (s_x.length <= pos_decimal + bitNum) {
            s_x += '0';
        }
        return s_x;
    }

    /**
     * 直营/非直营
     * @param agent
     * @returns {string}
     */
    function masterAgent(agent){
        if (agent == 1){
            return "直营";
        } else {
            return "非直营";
        }
    }

    function getFormatNum(flag, num, div, decimal) {
        return formatDecimal(num, div, decimal);
        /*if (flag === undefined) {
            return formatDecimal(num, div, decimal);
        } else {
            return "-"
        }*/
    }

    function formatDecimal(num, div, decimal) {
        if (num === "" || num == null) {
            return num;
        }
        num = (num / div).toString()
        let index = num.indexOf('.')
        if (index !== -1) {
            num = num.substring(0, decimal + index + 1)
        } else {
            num = num.substring(0)
        }
        return parseFloat(num).toFixed(decimal)
    }

    var createTableCols = (function () {
        var cols;

        if (json.isRework) {
            cols = [[
                {type: 'radio', hide: true},
                {
                    field: 'masterName',
                    title: '工程师（双击可选中工程师）',
                    sort: true,
                    templet: templeteFormatter.masterNameTempleteFunc
                },
                {field: 'starLevel', title: '星级', sort: true, align: 'center'},
                {
                    field: 'distance', title: '距离', sort: true, templet: function (data) {
                        return data.distance ? data.distance + 'KM' : '';
                    }
                },
                {field: 'monthReworkCount', title: '当月已派他人返修单', sort: true, align: 'center'},
                {field: 'handReworkCount', title: '手头返修单（不含待件&拉修）', sort: true, align: 'center'},
                {field: 'masterId', title: '占位列', hide: true, templet: templeteFormatter.masterInfoTempleteFunc}
            ]];
        } else {
            /*var normalColsData = [
                {type: 'radio', hide: true},
                {
                    field: 'masterName',
                    title: '工程师（双击可选中工程师）',
                    sort: true,
                    fixed: 'left',
                    minWidth: 290,
                    templet: templeteFormatter.masterNameTempleteFunc
                },
                {field: 'agent', title: '合作类型', sort: true, align: 'center' , templet:  function (data) { return masterAgent(data.agent)}},
                {field: 'starLevel', title: '星级', sort: true, align: 'center' , templet:  function (data) {
                        return nonDistributeAndDistributeFunc(data.nonDistributeFlag, data.starLevel)}
                },
                {
                    field: 'recommendScore', title: '系统推荐分', sort: true, align: 'center', templet: function (data) {
                        return nonDistributeAndDistributeFunc(data.nonDistributeFlag, data.recommendScore)
                    }
                },
                {
                    field: 'distance', title: '距离', sort: true, templet: function (data) {
                        if (data.agent == 1) {
                            if (weightMap['distanceWeight'] > 0) {
                                return nonDistributeAndDistributeFunc(data.nonDistributeFlag, data.distance ? data.distance + 'KM' : '')
                            } else {
                                return "-"
                            }
                        } else {
                            if (weightNonMap['distanceWeight'] > 0) {
                                return nonDistributeAndDistributeFunc(data.nonDistributeFlag, data.distance ? data.distance + 'KM' : '')
                            } else {
                                return "-"
                            }
                        }
                    }
                },
                {
                    field: 'handCountRatio',
                    title: '手头单占比',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        if (data.agent == 1) {
                            if (weightMap['handOrderWeight'] > 0) {
                                return nonDistributeAndDistributeFunc(data.nonDistributeFlag, data.handCountRatio + '%')
                            } else {
                                return "-"
                            }
                        } else {
                            if (weightNonMap['handOrderWeight'] > 0) {
                                return nonDistributeAndDistributeFunc(data.nonDistributeFlag, data.handCountRatio + '%')
                            } else {
                                return "-"
                            }
                        }
                    }
                },
                {
                    field: 'todaySuccessCount',
                    title: '今日完成',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        if (data.agent == 1) {
                            if (weightMap['todaySuccessWeight'] > 0) {
                                return nonDistributeAndDistributeFunc(data.nonDistributeFlag, data.todaySuccessCount)
                            } else {
                                return "-"
                            }
                        } else {
                            if (weightNonMap['todaySuccessWeight'] > 0) {
                                return nonDistributeAndDistributeFunc(data.nonDistributeFlag, data.todaySuccessCount)
                            } else {
                                return "-"
                            }
                        }
                    }
                },
                {
                    field: 'visitRate',
                    title: '上门率',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        if (data.agent == 1) {
                            if (weightMap['visitRateWeight'] > 0) {
                                return getFormatNum(data.nonDistributeFlag, data.visitRate, 100, 2) + '%'
                            } else {
                                return "-"
                            }
                        } else {
                            if (weightNonMap['visitRateWeight'] > 0) {
                                return getFormatNum(data.nonDistributeFlag, data.visitRate, 100, 2) + '%'
                            } else {
                                return "-"
                            }
                        }
                    }
                },
                {
                    field: 'successRate',
                    title: '成功率',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        if (data.agent == 1) {
                            if (weightMap['successRateWeight'] > 0) {
                                return getFormatNum(data.nonDistributeFlag, data.successRate, 100, 2) + '%'
                            } else {
                                return "-"
                            }
                        } else {
                            if (weightNonMap['successRateWeight'] > 0) {
                                return getFormatNum(data.nonDistributeFlag, data.successRate, 100, 2) + '%'
                            } else {
                                return "-"
                            }
                        }
                    }
                },
                {
                    field: 'atvAvg',
                    title: '客单价(元)',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        if (data.agent == 1) {
                            if (weightMap['avtAmountWeight'] > 0) {
                                return nonDistributeAndDistributeFunc(data.nonDistributeFlag, zmnUtils.unit.fenToYuan(data.atvAvg))
                            } else {
                                return "-"
                            }
                        } else {
                            if (weightNonMap['avtAmountWeight'] > 0) {
                                return nonDistributeAndDistributeFunc(data.nonDistributeFlag, zmnUtils.unit.fenToYuan(data.atvAvg))
                            } else {
                                return "-"
                            }
                        }
                    }
                },
                {
                    field: 'starLevelScore',
                    title: '星级分',
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        if (data.agent == 1) {
                            if (weightMap['starLevelScoreWeight'] > 0) {
                                return nonDistributeAndDistributeFunc(data.nonDistributeFlag, data.starLevelScore)
                            } else {
                                return "-"
                            }
                        } else {
                            if (weightNonMap['starLevelScoreWeight'] > 0) {
                                return nonDistributeAndDistributeFunc(data.nonDistributeFlag, data.starLevelScore)
                            } else {
                                return "-"
                            }
                        }
                    }
                },
                {
                    field: 'onlineStatus', title: '在线', sort: true, align: 'center', templet: function (data) {
                        return data.onlineStatus == 2 ? '<span class="layui-badge layui-bg-blue">在线</span>' : '<span class="layui-badge layui-bg-gray">离线</span>';
                    }
                },
                {field: 'engineerStatusName', title: '状态', sort: true, align: 'center'},
                {
                    field: 'mainSkillId', title: '主技能', sort: true, align: 'center', templet: function (data) {
                        return data.mainSkillId === json.mainSkillId ? '<span class="layui-badge layui-bg-blue">满足</span>' : '<span class="layui-badge layui-bg-gray">不满足</span>';
                    }
                },
                {field: 'checkServiceScope', title: '服务范围', sort: true, align: 'center',templet: function (data) { return  data.checkServiceScope == true ? '<span class="layui-badge layui-bg-blue">满足</span>' : '<span class="layui-badge layui-bg-gray">不满足</span>' ; }},
                {field: 'handCount', title: '手头单', sort: true, align: 'center' , templet: function (data) {return nonDistributeAndDistributeFunc(data.nonDistributeFlag,data.handCount)}},
                {field: 'masterId', title: '占位列', hide: true, templet: templeteFormatter.masterInfoTempleteFunc}
            ];*/

            var normalColsData = [
                {type: 'radio', hide: true},
                {
                    field: 'masterName',
                    title: '工程师（双击可选中工程师）',
                    sort: true,
                    fixed: 'left',
                    minWidth: 290,
                    templet: templeteFormatter.masterNameTempleteFunc
                },
                {field: 'agent', title: '合作类型', minWidth: 80, sort: true, align: 'center' , templet:  function (data) { return masterAgent(data.agent)}},
                {field: 'starLevel', minWidth:60, title: '星级', sort: true, align: 'center' },
                {field: 'recommendScore', title: '系统推荐分值', minWidth: 110, sort: true, align: 'center' },
                {field: 'distance', minWidth:60, title: '距离', sort: true, templet: function (data) {
                        return nonDistributeAndDistributeFunc(data.nonDistributeFlag, data.distance ? data.distance + 'KM' : '')
                    }
                },
                {field: 'datumOrderHourRatio', minWidth: 70, title: '单时比', sort: true, align: 'center' , templet:  function (data) { return processDatumOrderHourRatio(data.nonDistributeFlag , data.datumOrderHourRatio)}},
                {
                    field: 'handCountRatio',
                    title: '手头单占比',
                    minWidth: 100,
                    sort: true,
                    align: 'center',
                    templet: function (data) {
                        return nonDistributeAndDistributeFunc(data.nonDistributeFlag, data.handCountRatio + '%')
                    }
                },
                {field: 'distributeNewCount',minWidth: 110, title: '新单派单量', minWidth: 100, sort: true, align: 'center'},
                {field: 'starLevelScore', minWidth: 70, title: '星级分', sort: true, align: 'center' },
                {field: 'compositeScore', minWidth: 70, title: '服务分', sort: true, align: 'center'},
                {field: 'onlineStatus', minWidth:60, title: '在线', sort: true, align: 'center', templet: function (data) {
                        return data.onlineStatus == 2 ? '<span class="layui-badge layui-bg-blue">在线</span>' : '<span class="layui-badge layui-bg-gray">离线</span>';
                    }
                },
                {field: 'engineerStatusName', minWidth:60, title: '状态', sort: true, align: 'center'},
                {field: 'mainSkillId', minWidth: 70, title: '主技能', sort: true, align: 'center', templet: function (data) {
                        return data.mainSkillId === json.mainSkillId ? '<span class="layui-badge layui-bg-blue">满足</span>' : '<span class="layui-badge layui-bg-gray">不满足</span>';
                    }
                },
                { stockCity: 'stockCity', field: 'stockType', minWidth: 80, title: '最优库存', sort: true, align: 'center',templet: function (data) { return  processStockType(data.stockType); }},
                {field: 'handCount', minWidth: 70, title: '手头单', sort: true, align: 'center'},
                {field: 'masterId', title: '占位列', hide: true, templet: templeteFormatter.masterInfoTempleteFunc}
            ].filter((item) => {
                return !item.stockCity || json.stockCity;
            });

            cols = [normalColsData];
        }

        return function () {
            return cols;
        }
    })(json);

    /**
     * 打电话
     * @param masterId 工程师 id
     */
    function makeRadioCall(masterId) {
        var LOCAL_ITEM_NAME = 'distribute_voice_tips';
        var noTips = window.localStorage.getItem(LOCAL_ITEM_NAME);

        if (noTips === 'off') {
            zmnUtils.makeCall({masterId: masterId});
            return;
        }

        //自定页
        layer.open({
            type: 1,
            title: '提示',
            skin: 'modal-distribute', //样式类名
            closeBtn: 1,
            anim: 2,
            area: '425px',
            shadeClose: true,
            content: $('#modal-voice-wrapper').html(),
            success: function ($layer, index) {
                $layer.find('.layui-btn').attr('lay-filter', 'form-modal');
                form.render();

                form.on('submit(form-modal)', function (data) {
                    if (data.field.noTips === 'on') {
                        window.localStorage.setItem(LOCAL_ITEM_NAME, 'off');
                    }
                    layer.close(index);
                    zmnUtils.makeCall({masterId: masterId});

                    return false;
                });
            }
        });
    }

    /**
     * 呼叫中心打电话
     * @param telephone
     */
    function makeCallCenterCall(telephone) {
        top.postMessage({
            type: 2,
            phone: telephone
        }, '*');
    }

    /**
     * 检查当前的派单状态
     */
    function checkDistributeState() {
        var def = $.Deferred();
        var hasMaster = !!json.masterId;

        if (hasMaster) {
            //自定页
            layer.open({
                type: 1,
                title: '提示', closeBtn: 1,
                skin: 'modal-distribute',
                closeBtn: 1,
                anim: 2,
                area: '425px',
                shadeClose: true,
                content: $('#modal-distribute-wrapper').html(),
                success: function ($layer, index) {
                    $layer.on('click', '#btn-confirm', function () {
                        def.resolve();
                        layer.close(index);
                    });

                    $layer.on('click', '#btn-cancel', function () {
                        def.reject();
                        layer.close(index);
                    });
                }
            });
        } else {
            def.resolve();
        }

        return def.promise();
    }

    /**
     * 检查工程师是否可派单
     */
    function checkMasterDistributable(params) {
        var def = $.Deferred();
        var masterId = +params.masterId;
        var master;

        // 如果是推荐派单
        if (json.recommendStatus && !json.simpleStatus) {
            master = json.recommendMasterList.find(function (item) {
                return item.masterId === masterId;
            });
        } else {
            // 如果是简单派单先走简单派单
            master = json.masterList.find(function (item) {
                return item.masterId === masterId;
            });
        }

        if (master) {
            def.resolve(masterId, '可派单');
        } else {
            $http.get(MASTER_CHECK_URL, params).then(function (data) {
                if (data.status === 2) {
                    def.resolve(masterId, data.reason);
                } else {
                    def.reject(data.reason);
                }
            }, function (msg) {
                layer.msg(msg);
                def.reject('校验失败');
            });
        }

        return def.promise();
    }

    /**
     * 使用 Select2 初始化工程师下拉框
     */
    function initMasterSelecteBySelect2() {
        select2.initRemote({
            el: '#select-master',
            url: MASTER_LIST_URL,
            placeholder: '输入工程师姓名校验是否可派单',
            getParams: function (params) {
                return {
                    text: params.term,
                    companyId: $('#companyId').val(),
                    manageCompanyId: $('#manageCompanyId').val(),
                    cityId: $('#cityId').val(),
                    plat: json.plat
                };
            },
            processor: function (data) {
                return data.map((item) => {
                    item.id = item.value;
                    return item;
                });
            },
            formatRepo: formatRepoForMaster
        });
    }

    /**
     * 格式化工程师列表列表项
     * @param {object} repo
     * @returns {string}
     */
    function formatRepoForMaster(repo) {
        if (repo.loading) {
            return '查询中...'
        }
        var name = repo.text + (repo.disabled ? '（离职）' : '');
        var markup = '<div><div><i class="zmn-icon zmn-icon-worker"></i><span>' + name + '</span></div><div><i class="zmn-icon zmn-icon-phone"></i><span>' + repo.ext1 + '</span></div></div>';

        return markup;
    }

    /**配件综合成本总额
     * 根据分组 id 筛选推荐工程师
     * @param masterList
     * @param mainSkillId 主技能id
     * @returns {array}
     */
    function filtrateMasterListByGroupId(masterList, mainSkillId) {
        return masterList.filter((item) => {
            return item.mainSkillId === mainSkillId;
        }).map((item) => {
            if (item.masterId === json.masterId) {
                item['LAY_CHECKED'] = true;
            }
            return item;
        });
    }

    function renderSimpleMasterList(data) {
        table.render({
            elem: '#simpleMasterTable',
            height: 400,
            limit: 1000,
            data: data || [],
            skin: 'line',
            cols: [[
                {type: 'radio', hide: true},
                {field: 'masterName', title: '工程师（双击可选中工程师）', templet: templeteFormatter.MapMasterNameTempleteFunc},
                {field: 'masterId', title: '占位列', hide: true, templet: templeteFormatter.masterInfoTempleteFunc}
            ]]
        });
    }

    function renderDetailMasterList(data) {
        table.render({
            elem: '#detailMasterTable',
            height: 400,
            limit: 1000,
            data: data,
            skin: 'line',
            cols: createTableCols(),
            done: function (res, curr, count) {
                var re = res.data;
                if (re.length > 0) {
                    for (var i in res.data) {
                        var item = res.data[i];
                        if (item.nonDistributeFlag != undefined) {
                            $('tr[data-index=' + i + ']').prop('disabled', true);
                            $("tr[data-index='" + i + "']").attr({"style": "background:#F2F2F2;color:#999999"});  //将当前行变成绿色
                        }
                    }
                }
            }
        });
    }

    function renderMasterPointsOfMap(data) {
        var map = new BMap.Map("mapOfmaterList");
        var point = new BMap.Point(json.orderLocation.lng, json.orderLocation.lat);
        map.centerAndZoom(point, 12);
        map.enableScrollWheelZoom(true);
        map.addControl(new BMap.NavigationControl({
            anchor: BMAP_ANCHOR_TOP_RIGHT,
            type: BMAP_NAVIGATION_CONTROL_ZOOM
        }));
        map.addControl(new BMap.OverviewMapControl());

        addMakerForCustomer(map, point);
        addMakerListForMaster(map, data);
    }


    function addMakerForCustomer(map, point) {
        var marker = new BMap.Marker(point, {
            icon: new BMap.Icon('/static/images/icon-repair.png', new BMap.Size(32, 32), {
                // offset: new BMap.Size(10, 25), // 指定定位位置
                imageSize: new BMap.Size(32, 32)
            })
        });
        map.addOverlay(marker);

        var label = new BMap.Label(json.dutyInfo, {
            offset: new BMap.Size(0, -20)
        });
        label.setStyle({
            border: 'none',
            color: '#fff',
            backgroundColor: '#01AAED'
        });

        marker.setLabel(label);

        setInterval(function () {
            var rotation = marker.getRotation();
            marker.setRotation(rotation + 30);
        }, 100);
    }

    function addMakerListForMaster(map, data) {
        if (!data) {
            return;
        }
        makerList = [];
        var nearestMaster = data.reduce((acc, curr) => {
            if (curr.distance <= acc.distance) {
                return curr;
            }

            return acc;
        }, {});

        data.forEach((master) => {
            var point = new BMap.Point(master.masterLng, master.masterLat);
            var marker = new BMap.Marker(point, {
                icon: new BMap.Icon('/static/images/icon-master.png', new BMap.Size(70, 70), {
                    // offset: new BMap.Size(10, 25), // 指定定位位置
                    imageSize: new BMap.Size(70, 70)
                })
            });

            marker.addEventListener('click', function () {
                var masterId = master.masterId;
                updateMasterSelect(masterId, null);
                updateMasterListTable(masterId);
                updateVoiceStatus(false);
            });

            if (nearestMaster.masterId === master.masterId) {
                var label = new BMap.Label('距离最近：' + master.distance, {
                    offset: new BMap.Size(0, -20)
                });

                label.setStyle({
                    border: 'none',
                    color: '#fff',
                    backgroundColor: '#01AAED'
                });

                marker.setLabel(label);
            }

            map.addOverlay(marker);

            makerList.push(marker);

            if (master.masterId === json.masterId) {
                marker.setAnimation(BMAP_ANIMATION_BOUNCE);
            }
        })
    }

    function initMapViewOfMasterList(data) {
        try {
            renderMasterPointsOfMap(data);
        } catch (e) {
            console.log(e);
        }

        renderSimpleMasterList(data);
    }

    function initTableViewOfMasterList(data) {
        renderDetailMasterList(data);
    }

    function updateMasterSelect(masterId, masterInfo) {
        //$('#masterSelect').val(masterId);
        form.val('zmn-work-form', {masterId: masterId});
        $('#masterId').val(masterInfo);
        // form.render();
    }

    function updateMasterListTable(masterId) {
        var tableWrapperList = $('#mapView, #tableView');

        tableWrapperList.find('input[type="radio"]').prop('checked', false);
        tableWrapperList.find('.layui-table-main tr.current').removeClass('current');
        tableWrapperList.find('span.master[id="' + masterId + '"]')
            .closest('tr')
            .addClass('current')
            .find('input[type="radio"]')
            .prop('checked', true);
        form.render('radio');

        allMasterList.forEach((master) => {
            if (master.masterId === +masterId) {
                master['LAY_CHECKED'] = true;
            } else {
                master['LAY_CHECKED'] = false;
            }
        });
    }

    /**
     * 更新语音按钮状态
     * @param {boolean} disabled 是否禁用
     */
    function updateVoiceStatus(disabled) {
        var $voiceBtn = $('.zmn-btn-voice');
        $voiceBtn.prop('disabled', disabled);

        if (disabled) {
            $voiceBtn.addClass('layui-btn-disabled');
        } else {
            $voiceBtn.removeClass('layui-btn-disabled');
        }
    }


    /**
     * 初始化页面
     */
    function initPage() {


        if (json.isRework) {
            initTableViewOfMasterList(json.masterList);
        } else if (json.recommendStatus) {
            // 设置不可派单师傅标示
            var resultList = json.nonDistributeMasterList
            if (resultList !== null) {
                resultList.forEach(item => {
                    item.nonDistributeFlag = 2;
                })
                initTableViewOfMasterList(allMasterList.concat(resultList));
            } else {
                initTableViewOfMasterList(allMasterList);
            }
            initMapViewOfMasterList(allMasterList);
            updateMasterListTable(json.masterId);
        }

    }

    /**
     * 初始化页面事件
     */
    // function initEvent() {
    //     // 改派缘由
    //     form.on('radio(distributeReason)', function(obj) {
    //         if (obj.elem.checked) {
    //             $('#liableTypeName').text($(this).data('liable-type-name'));
    //         } else {
    //             $('#liableTypeName').text('');
    //         }
    //     });
    //
    //     form.on('submit(distribute)', function (data) {
    //         if (data.field.masterId === '') {
    //             layer.msg('请选择工程师');
    //             return false;
    //         }
    //         if (!!json.masterId) {
    //             if (!data.field.distributeReasonId) {
    //                 layer.msg('请选择改派缘由');
    //                 return false;
    //             }
    //             // 获取改派缘由
    //             let $distributeReason = $('input[name="distributeReasonId"]:checked');
    //             data.field.distributeReason = $distributeReason.attr('title');
    //             data.field.liableType = $distributeReason.data('liable-type');
    //         }
    //
    //         checkDistributeState().then(function () {
    //             $http.lockSave(data.form.action, data.field, data.elem).then(function () {
    //                 layer.msg('派单保存成功', {icon: 1, time: 1000}, function () {
    //                     opCommonUtils.goOperateHome();
    //                 });
    //             }, function (msg) {
    //                 layer.msg(msg);
    //             });
    //         });
    //
    //         return false;
    //     });
    //
    //     // 监听网络电话按钮
    //     form.on('submit(call)', function (data) {
    //         var masterId = data.field.masterId;
    //         if (masterId === '') {
    //             layer.msg('请选择工程师');
    //             return false;
    //         }
    //         makeRadioCall(masterId);
    //         return false;
    //     });
    //
    //     // 初始化呼叫电话组件
    //     (function initCallForCC() {
    //         if (!top.isCallCenter) {
    //             return;
    //         }
    //
    //         $('#btn-cc-call').removeClass('layui-hide');
    //
    //         // 监听呼叫电话按钮
    //         form.on('submit(cc-call)', function (data) {
    //             var masterId = data.field.masterId;
    //             if (masterId === '') {
    //                 layer.msg('请选择工程师');
    //                 return false;
    //             }
    //
    //             var $option = $('#masterSelect option[value="' + masterId + '"]');
    //             var telephone = $option.data('telephone');
    //             if (telephone) {
    //                 makeCallCenterCall($option.data('telephone'));
    //             } else {
    //                 $api.masterGetDetail({masterId: masterId}).then((info) => {
    //                     var telephone = info.mobile;
    //                     $option.data('telephone', telephone);
    //                     makeCallCenterCall(telephone);
    //                 }, (msg) => {
    //                     zmnUtils.layui.toastError('工程师电话获取失败');
    //                 });
    //             }
    //
    //             return false;
    //         });
    //     }());
    //
    //     form.on('select(masterSelect)', function (data) {
    //         var masterId = data.value;
    //
    //         updateMasterListTable(masterId);
    //         updateVoiceStatus(!masterId);
    //     });
    //
    //     form.on('submit(check-master)', function (data) {
    //         var masterId = $('#select-master').val();
    //         var params = data.field;
    //         if (!masterId) {
    //             zmnUtils.layui.toastError('请先选择要校验的工程师');
    //             return false;
    //         }
    //         params.masterId = masterId;
    //
    //         var setCheckResultMessage = function (result, msg) {
    //             $('#master-check-msg').removeAttr('class')
    //                 .addClass(result)
    //                 .text(msg);
    //         };
    //
    //         checkMasterDistributable(params).then(function (masterId, msg) {
    //             setCheckResultMessage('success', msg);
    //         }, function (msg) {
    //             setCheckResultMessage('fail', msg);
    //         });
    //
    //         return false;
    //     });
    //
    //     $('#mapView, #tableView').on('click', 'button', function (e) {
    //         var $this = $(this);
    //         $this.removeClass('layui-btn-primary')
    //             .siblings()
    //             .addClass('layui-btn-primary');
    //
    //         var data = $this.data('id') ? partMaterList : allMasterList;
    //
    //         if (e.delegateTarget.id === 'mapView') {
    //             initMapViewOfMasterList(data);
    //         } else if (e.delegateTarget.id === 'tableView') {
    //             initTableViewOfMasterList(data);
    //         }
    //     });
    //
    //     table.on('radio(tableOfMatserList)', function (obj) {
    //         var masterId = obj.data.masterId;
    //         var masterInfo = obj.data.masterName + '—' + zmnUtils.maskPhone(obj.data.masterPhone);
    //         updateMasterSelect(masterId, masterInfo);
    //         updateVoiceStatus(!masterId);
    //     });
    //
    //     table.on('rowDouble(tableOfMatserList)', function (obj) {
    //         var $this = $(obj.tr);
    //         $this.addClass('current')
    //             .siblings('tr')
    //             .removeClass('current');
    //
    //         if (obj.data !== null && obj.data.nonDistributeFlag === undefined) {
    //             $this.find('.layui-form-radio .layui-icon').trigger('click');
    //         }
    //     });
    //
    //     // 初始化电话组件
    //     $('body').on('click', '.btn-netcall', function () {
    //         var masterId = $(this).data('id');
    //         makeRadioCall(masterId);
    //     });
    //
    //     // 弹出工程师库存
    //     $('body').on('click', '.btn-stock', function () {
    //         var masterId = $(this).data('id');
    //         var workId = $("#workId").val();
    //         var orderId = $("#orderId").val();
    //
    //         $http.get(GET_MASTER_STOCK_URL, {masterId : masterId,workId : workId, orderId: orderId}).then(function (data) {
    //             var tableStr = '<table class="layui-table" id="shipList" style="width: 90%" lay-filter="shipList">';
    //             var oneTr = '<tr>';
    //             var twoTr = '<tr>';
    //             data.forEach((value, index) => {
    //                 if (value.isTakeUp == 2) {
    //                     oneTr += '<td style="background-color: #999999; min-width: 75px; max-width: 200px; line-height: 36px; height: 36px"></td>';
    //                 }else {
    //                     oneTr += '<td style="background-color: #ffffff; min-width: 75px; max-width: 200px; line-height: 36px; height: 36px"></td>';
    //                 }
    //
    //                 twoTr += '<td style="min-width: 75px; max-width: 200px; line-height: 36px; height: 36px">' +
    //                     value.startTime + '-' + value.endTime +
    //                     '</td>';
    //             });
    //             oneTr += '</tr>';
    //             twoTr += '</tr>';
    //
    //             tableStr += oneTr + twoTr +
    //                 '</tbody>' +
    //                 '</table>';
    //
    //             layer.open({
    //                 type: 1,
    //                 title: "库存",
    //                 shade: 0,
    //                 resizing: function () {
    //                     table.resize('shipList');
    //                 },
    //                 resize: true,
    //                 area: ['70%', '180px'],
    //                 content: tableStr
    //             });
    //         }, function (msg) {
    //             layer.msg(msg);
    //         });
    //     });
    // }

    /**
     * 初始化页面事件
     */
    function initEvent() {
        // 改派缘由
        form.on('radio(distributeReason)', function(obj) {
            if (obj.elem.checked) {
                $('#liableTypeName').text($(this).data('liable-type-name'));
            } else {
                $('#liableTypeName').text('');
            }
        });

        form.on('submit(distribute)', function (data) {
            if (data.field.masterId === '') {
                layer.msg('请选择工程师');
                return false;
            }
            if (!!json.masterId) {
                if (!data.field.distributeReasonId) {
                    layer.msg('请选择改派缘由');
                    return false;
                }
                // 获取改派缘由
                let $distributeReason = $('input[name="distributeReasonId"]:checked');
                data.field.distributeReason = $distributeReason.attr('title');
                data.field.liableType = $distributeReason.data('liable-type');
            }

            checkDistributeState().then(function () {
                $http.lockSave(data.form.action, data.field, data.elem).then(function () {
                    layer.msg('派单保存成功', {icon: 1, time: 1000}, function () {
                        opCommonUtils.goOperateHome();
                    });
                }, function (msg) {
                    layer.msg(msg);
                });
            });

            return false;
        });

        // 监听网络电话按钮
        form.on('submit(call)', function (data) {
            var masterId = data.field.masterId;
            if (masterId === '') {
                layer.msg('请选择工程师');
                return false;
            }
            makeRadioCall(masterId);
            return false;
        });

        // 初始化呼叫电话组件
        (function initCallForCC() {
            if (!top.isCallCenter) {
                return;
            }

            $('#btn-cc-call').removeClass('layui-hide');

            // 监听呼叫电话按钮
            form.on('submit(cc-call)', function (data) {
                var masterId = data.field.masterId;
                if (masterId === '') {
                    layer.msg('请选择工程师');
                    return false;
                }

                var $option = $('#masterSelect option[value="' + masterId + '"]');
                var telephone = $option.data('telephone');
                if (telephone) {
                    makeCallCenterCall($option.data('telephone'));
                } else {
                    $api.masterGetDetail({masterId: masterId}).then((info) => {
                        var telephone = info.mobile;
                        $option.data('telephone', telephone);
                        makeCallCenterCall(telephone);
                    }, (msg) => {
                        zmnUtils.layui.toastError('工程师电话获取失败');
                    });
                }

                return false;
            });
        }());

        form.on('select(masterSelect)', function (data) {
            var masterId = data.value;

            updateMasterListTable(masterId);
            updateVoiceStatus(!masterId);
        });

        form.on('submit(check-master)', function (data) {
            var masterId = $('#select-master').val();
            var params = data.field;
            if (!masterId) {
                zmnUtils.layui.toastError('请先选择要校验的工程师');
                return false;
            }
            params.masterId = masterId;

            var setCheckResultMessage = function (result, msg) {
                $('#master-check-msg').removeAttr('class')
                    .addClass(result)
                    .text(msg);
            };

            checkMasterDistributable(params).then(function (masterId, msg) {
                setCheckResultMessage('success', msg);
            }, function (msg) {
                setCheckResultMessage('fail', msg);
            });

            return false;
        });

        $('#mapView, #tableView').on('click', 'button', function (e) {
            var $this = $(this);
            $this.removeClass('layui-btn-primary')
                .siblings()
                .addClass('layui-btn-primary');

            var data = $this.data('id') ? partMaterList : allMasterList;

            if (e.delegateTarget.id === 'mapView') {
                initMapViewOfMasterList(data);
            } else if (e.delegateTarget.id === 'tableView') {
                initTableViewOfMasterList(data);
            }
        });

        table.on('radio(tableOfMatserList)', function (obj) {
            var masterId = obj.data.masterId;
            var masterInfo = obj.data.masterName + '—' + zmnUtils.maskPhone(obj.data.masterPhone);
            updateMasterSelect(masterId, masterInfo);
            updateVoiceStatus(!masterId);
        });

        table.on('rowDouble(tableOfMatserList)', function (obj) {
            var $this = $(obj.tr);
            $this.addClass('current')
                .siblings('tr')
                .removeClass('current');

            if (obj.data !== null && obj.data.nonDistributeFlag === undefined) {
                $this.find('.layui-form-radio .layui-icon').trigger('click');
            }

        });

        // 初始化电话组件
        $('body').on('click', '.btn-netcall', function () {
            var masterId = $(this).data('id');
            makeRadioCall(masterId);
        });

        // 弹出工程师库存
        $('body').on('click', '.btn-stock', function () {
            var masterId = $(this).data('id');
            var workId = $("#workId").val();
            var orderId = $("#orderId").val();

            $http.get(GET_MASTER_STOCK_URL, {masterId : masterId,workId : workId, orderId: orderId}).then(function (data) {
                var tableStr = '<table class="layui-table" id="shipList" style="width: 90%" lay-filter="shipList">';
                var oneTr = '<tr>';
                var twoTr = '<tr>';
                data.forEach((value, index) => {
                    if (value.isTakeUp == 2) {
                        oneTr += '<td style="background-color: #999999; min-width: 75px; max-width: 200px; line-height: 36px; height: 36px"></td>';
                    }else {
                        oneTr += '<td style="background-color: #ffffff; min-width: 75px; max-width: 200px; line-height: 36px; height: 36px"></td>';
                    }

                    twoTr += '<td style="min-width: 75px; max-width: 200px; line-height: 36px; height: 36px">' +
                        value.startTime + '-' + value.endTime +
                        '</td>';
                });
                oneTr += '</tr>';
                twoTr += '</tr>';

                tableStr += oneTr + twoTr +
                    '</tbody>' +
                    '</table>';

                layer.open({
                    type: 1,
                    title: "库存",
                    shade: 0,
                    resizing: function () {
                        table.resize('shipList');
                    },
                    resize: true,
                    area: ['70%', '180px'],
                    content: tableStr
                });
            }, function (msg) {
                layer.msg(msg);
            });
        });
    }



    // 程序入口
    function init() {

        // 初始化页面
        initPage();

        initMasterSelecteBySelect2();

        // 初始化事件
        initEvent();


    }


    // 初始化
    init();

    exports('oms_work_modify_biztypec_distribute');
});